import {
	clearStorage,
	removeAllCookie,
	setStorage,
	removeCookie,
	getStorage
} from '@/utils/setStorage.js';
import {
	encryptDes
} from '@/utils/des.js';
const baseUrl = 'http://superant.yuntai-test.com/'
// const baseUrl = 'http://www.ctwcargo.net/'
// const baseUrl = 'http://120.25.173.224:8999/'
// const baseUrl = 'http://ctwcargo.com/'

let ajaxTimes = 0;

// 截取cookie值
function getHeaders() {
	let token = getStorage('token') || ''
	let header = {
		"x-super-ant-token": token,
		// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
		'Content-Type': 'application/json'

	}
	return header
}

var loadingTimeBox = null

const http = (state, url, param, method, cd) => {
	ajaxTimes++;
	// uni.showLoading({
	// 	title: "加载中",
	// 	mask: true,
	// });
	loadingTimeBox = setTimeout(() => {
		uni.hideLoading();
	}, 5000)
	return new Promise((resolve, reject) => {
		var abortRequest = uni.request({
			method: method || 'POST',
			url: state ? baseUrl + url : url,
			data: param,
			header: getHeaders(),
			success: (res) => {
				// 判断token失效时状态码，跳转回首页
				if (res.data.errno === 501) {
					let num = ''
					if (getStorage('tokenNum')) {
						num = getStorage('tokenNum').value || 1
					} else {
						num = 1
					}
					if (num === 1) {
						const obj = {
							type: 'login',
							value: 2
						};
						setStorage('tokenNum', obj);
						uni.showModal({
							title: 'Tips',
							content: 'Login timeout, please login again!',
							confirmText: 'confirm',
							confirmColor: '#EE8F57',
							showCancel: false,
							success: function(res2) {
								if (res2.confirm == true) {
									const lang = getStorage('language') || 'th';
									clearStorage();
									removeAllCookie();
									removeCookie(baseUrl);
									// 多语言重新赋值
									setTimeout(() => {
										setStorage('language', lang);
										setStorage('showLoginBox', true);
										const obj = {
											type: 'login',
											value: 1
										};
										setStorage('tokenNum', obj);
										// #ifdef APP-PLUS
										uni.reLaunch({
											url: '/pages/home/index'
										});
										// #endif
										// #ifdef H5
										this.$Router.push(
											'/pages/home/index');
										// #endif
									}, 300);
								}
							}
						});
					}
					return resolve(res)
				} else {
					return resolve(res)
				}
			},
			fail: (err) => {
				if (err.errMsg != 'request:fail abort') {
					uni.showToast({
						title: 'Network error!',
						icon: 'none',
						position: 'top'
					});
				}
				console.log(err, '请求错误')
				return reject(err)
			},
			// 完成之后关闭加载效果
			complete: (s) => {
				// return resolve(s)
				clearTimeout(loadingTimeBox)
				ajaxTimes--;
				if (ajaxTimes === 0) {
					//  关闭正在等待的图标
					uni.hideLoading();
				}
			}
		})
		if (cd) {
			cd(abortRequest)
		}
	})
}

export {
	http,
	baseUrl
}
